﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Configuration;

public partial class sistema_cotizacion_frmAdministrarComisiones : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            bool hayFile = false;
            string SavePath, Msg = null, nomFile = "";
            //string _Path = HttpContext.Current.Request.ApplicationPath.ToString();
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    //SavePath = _Path + ConfigurationManager.AppSettings["PatientPhotoImages"].ToString() + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    //hpf.SaveAs(Server.MapPath(SavePath));
                    nomFile = GetUniqueKey() + GetFileExtension(hpf.FileName);
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString() + nomFile;
                    hpf.SaveAs(SavePath);
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                    hayFile = true;
                }
            }
            if (hayFile)
            {
                lblMsg.Text = Msg + " Uploaded Successfully.";
                hdArchivo.Value = nomFile;
            }
            else
            {
                lblMsg.Text = "";
                hdArchivo.Value = "";
            }
        }
    }

    private string GetFileExtension(string FileName)
    {
        char saperator = '.';
        string[] temp = FileName.Split(saperator);
        return "." + temp[1].ToString();
    }

    private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;
        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        chars = a.ToCharArray();
        int size = maxSize;
        byte[] data = new byte[1];
        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }
        return result.ToString();
    }

    private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

    private bool ServerSideValidation()
    {
        string errorMsg = string.Empty, temp = null;
        bool errorFlag = true;
        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if (temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }
        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

    private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.
        if (!IsValidFile(myFile.FileName))
        {
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

    private bool IsValidFile(string filePath)
    {
        bool isValid = false;
        string[] fileExtensions = { ".CSV" };
        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.ToUpper().Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }
}